package com.itx77.service;

import com.itx77.dao.AppCategoryDao;
import com.itx77.entity.AppCategory;
import com.itx77.vo.CategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: .x77
 * @CreateTime:2023/12/8 8:54
 */
@Service
public class CategoryService {
    @Autowired
    AppCategoryDao appCategoryDao;

    public CategoryVo Tree(){
        List<AppCategory> list = appCategoryDao.query(new AppCategory());
        List<CategoryVo> tree = new ArrayList<>();
        for (AppCategory appCategory : list) {
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setId(appCategory.getId());
            categoryVo.setCategoryname(appCategory.getCategoryname());
            categoryVo.setParentid(appCategory.getParentid());
            tree.add(categoryVo);
        }
        CategoryVo categoryVo = new CategoryVo();
        for (CategoryVo vo : tree) {
            if (vo.getParentid() == null){
                categoryVo = category(vo,tree);
            }
        }
        return categoryVo;
    }

    private CategoryVo category(CategoryVo vo, List<CategoryVo> tree) {
        vo.setCategoryList(new ArrayList<>());
        for (CategoryVo categoryVo : tree) {
            if (vo.getId() == categoryVo.getParentid()){
                vo.getCategoryList().add(categoryVo);
                category(categoryVo,tree);
            }
        }
        return vo;
    }
}
